import { getNodeStyle } from "../utils/tools"


export default {
  mounted(el, binding) {
    // console.log(el, binding);
    const oImgWrap = el,
          oMagWrap = oImgWrap.querySelector('.mag-wrap'),
          oMagImg = oMagWrap.querySelector('.mag-img'),
          imgWidth = getNodeStyle(oImgWrap, 'width'),
          imgHeight = getNodeStyle(oImgWrap, 'height'),
          magWidth = getNodeStyle(oMagWrap, 'width'),
          magHeight = getNodeStyle(oMagWrap, 'height'),
          imgX = oImgWrap.offsetLeft,
          imgY = oImgWrap.offsetTop;

    // console.log(imgWidth, imgHeight)
    // console.log(imgX, imgY);

    const init = () => {
      bindEvent()
    }

    function bindEvent() {
      oImgWrap.addEventListener('mouseover', function(e) {
        oMagWrap.className += ' show';
        // console.log(e.pageX, imgX, magWidth / 2, e.pageX - imgX - magWidth / 2)
        const { x, y } = getXY(e);
        showMag(x, y);

        document.addEventListener('mousemove', handleMouseMove, false);
      }, false);

      oImgWrap.addEventListener('mouseout', handleMouseOut, false);
    }

    function handleMouseMove(e) {
      const { x, y, mouseX, mouseY } = getXY(e);
      showMag(x, y, mouseX, mouseY);
    }

    function handleMouseOut() {
      oMagWrap.className = 'mag-wrap';
      document.removeEventListener('mousemove', handleMouseMove, false);
    }

    function showMag(x, y, mouseX, mouseY) {
      oMagWrap.style.left = x + 'px';
      oMagWrap.style.top = y + 'px';
      oMagImg.style.left = - x + 'px';
      oMagImg.style.top = - y + 'px';

      if ( mouseX < 0 || mouseY < 0 // 限制放大框的移动超出就隐藏
        || mouseX > imgWidth || mouseY > imgHeight
      ) {
        oMagWrap.className = 'mag-wrap';
        document.removeEventListener('mousemove', handleMouseMove, false);
      }
    }

    function getXY(e) {
      return {
        x: e.pageX - imgX - magWidth / 2,
        y: e.pageY - imgY - magHeight / 2,
        mouseX: e.pageX - imgX,
        mouseY: e.pageY - imgY
      }
    }

    init();
  },
  updated(el, binding) {

  }
}